import React, { Component } from 'react'
import { connect } from 'dva'
import {
  Select,
  TreeSelect,
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  DatePicker,
  Upload,
  Icon,
  message,
  Modal,
} from 'antd'
import moment from 'moment'
import Cookies from 'universal-cookie'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import styles from './Index.less'
import { uploadDataConvert, itemConvertToUpload } from '@/utils/utils'

const FormItem = Form.Item
const { TreeNode } = TreeSelect
const { Option } = Select
const { TextArea } = Input

const cookies = new Cookies()

@connect(({ loading, property, settings, department, account }) => ({
  property,
  settings,
  department,
  account,
  loading: loading.models.property,
}))
@Form.create()
export default class PropUpdate extends Component {
  constructor(props) {
    super(props)

    const fileImgList = []
    const fileFileList = []

    this.state = {
      fileImgList,
      fileFileList,
    }
  }

  // 组件加载完成后加载数据
  componentDidMount() {
    const { dispatch } = this.props
    const { currentItem } = this.props.property
    const propSelectKeys = ['property_status', 'property_class', 'location_seat']
    // 获取状态select数据
    // 资产分类select数据
    // 获取位置select数据
    propSelectKeys.forEach(key => {
      dispatch({
        type: 'property/fetchSelectPropData',
        payload: {
          type: key,
        },
      })
    })

    dispatch({
      type: 'department/listOrg',
    })

    if (currentItem.orgId) {
      this.props.dispatch({
        type: 'account/fetchUsersByOrgId',
        payload: currentItem.orgId,
      })
    }
    // 用户
    // dispatch({
    //   type: 'account/fetch',
    //   payload: {
    //     pageSize: 100,
    //   },
    // })

    if (currentItem.id && currentItem.items) {
      this.setState({
        fileImgList: itemConvertToUpload('2', currentItem.items),
        fileFileList: itemConvertToUpload('1', currentItem.items),
      })
    }
  }

  componentDidUpdate(prevProps) {
    if (prevProps.property.currentItem.id && !this.props.property.currentItem.id) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({
        fileImgList: [],
        fileFileList: [],
      })
    }
  }

  // 文件上传
  handleUplod = (f, type) => {
    if (f.file.status) {
      this.setState({
        [type]: f.fileList,
      })
    }
    if (f.file.status === 'done') {
      if (!f.file.response.success) {
        Modal.error({
          title: '上传错误',
          content: f.file.response.message,
        })
      }
    }
  }

  handleBeforeUpload = file => {
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      message.error('文件小于10M')
      return false
    }
  }

  handleDepChange = value => {
    const { resetFields, setFieldsValue } = this.props.form
    const { currentItem } = this.props.property
    this.props.dispatch({
      type: 'account/fetchUsersByOrgId',
      payload: value,
      callback: () => {
        resetFields(['useOperator'])
        if (currentItem.useOperator) {
          setFieldsValue({ useOperator: '' })
        }
      },
    })
  }

  handleSave() {
    const { dispatch } = this.props
    const { currentItem } = this.props.property
    const { getFieldsValue, validateFields } = this.props.form
    const queryState = this.props.location.state
    let parLevel = null
    // let pzcCode = null
    // // 增加子资产
    if (queryState) {
      parLevel = queryState.pid
    }

    validateFields(errors => {
      if (errors) {
        return
      }

      const data = {
        ...getFieldsValue(),
        id: currentItem.id,
        items: [],
      }
      data.gmtRk = data.gmtRk ? data.gmtRk.format('YYYY-MM-DD') : undefined

      if (data.filesImg && data.filesImg.fileList && data.filesImg.fileList.length > 0) {
        data.filesImg.fileList.forEach((item, index) => {
          const res = uploadDataConvert(item, index, '2')
          if (res.success) {
            data.items.push(res.data)
          }
        })
      }

      if (data.filesfile && data.filesfile.fileList && data.filesfile.fileList.length > 0) {
        const res = uploadDataConvert(data.filesfile.fileList[0], 1, '1')
        if (res.success) {
          data.items.push(res.data)
        }
      }

      delete data.filesImg
      delete data.filesfile

      // parLevel主资产id 添加子资产,子资产修改时传 (新增资产,修改主资产不传)
      if (parLevel || (currentItem.zcType && currentItem.zcType === '0002')) {
        data.parLevel = currentItem.parLevel || parLevel || undefined
      }

      dispatch({
        type: 'property/save',
        payload: data,
      })
    })
  }

  // 资产属性下拉option
  renderOptionNodes(type) {
    const data = this.props.property[type]
    return data.map(item => (
      <Option key={item.id} value={item.keyName}>
        {item.keyValue}
      </Option>
    ))
  }

  // 渲染部门树节点
  renderTreeNodes(data) {
    // 排除根节点
    if (data[0] && data[0].parentId === '0') {
      data = data[0].children
    }
    return data
      .map(item => {
        if (item.status === '0001') {
          if (item.children) {
            return (
              // 此处查询用 id
              <TreeNode title={item.name} key={item.id} value={item.id}>
                {this.renderTreeNodes(item.children)}
              </TreeNode>
            )
          }
          return <TreeNode title={item.name} key={item.id} value={item.id} />
        }
        return null
      })
      .filter(item => item || false)
  }

  // 简单搜索条件
  renderForm() {
    const { settings } = this.props
    const { fileFileList, fileImgList } = this.state
    const { currentItem } = this.props.property
    const depData = this.props.department.data
    const { usersByOrgId } = this.props.account
    const { getFieldDecorator } = this.props.form
    // const queryState = this.props.location.state
    // let pzcCode = null
    // // 增加子资产
    // if (queryState) {
    //   pzcCode = queryState.p_zcCode
    // }

    const AuthHeaders = {
      Authorization: `Bearer${cookies.get('auth_token')}`,
    }

    return (
      <Form layout="inline">
        <div className={styles.fieldTitle}>基本信息</div>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="资产编码">
              {getFieldDecorator('zcCode', {
                initialValue: currentItem.zcCode,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Input placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
          <div>
            <span style={{ lineHeight: '32px' }}>主资产编码需与SAP系统保持一致</span>
          </div>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="资产名称">
              {getFieldDecorator('zcName', {
                initialValue: currentItem.zcName,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Input placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="型号/规格">
              {getFieldDecorator('specification', {
                initialValue: currentItem.specification,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Input placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="资产分类">
              {getFieldDecorator('zcClass', {
                initialValue: currentItem.zcClass,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Select placeholder="请选择">{this.renderOptionNodes('property_class')}</Select>)}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="入库时间">
              {getFieldDecorator('gmtRk', {
                initialValue: currentItem.gmtRk ? moment(currentItem.gmtRk, 'YYYY-MM-DD') : null,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<DatePicker></DatePicker>)}
            </FormItem>
          </Col>
        </Row>
        <div className={styles.fieldTitle}>使用信息</div>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="使用部门">
              {getFieldDecorator('orgId', {
                initialValue: currentItem.orgId,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(
                <TreeSelect
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  showCheckedStrategy={TreeSelect.SHOW_ALL}
                  allowClear
                  showSearch
                  treeNodeFilterProp="title"
                  placeholder="请选择所属部门节点"
                  onChange={this.handleDepChange}
                >
                  {this.renderTreeNodes(depData)}
                </TreeSelect>,
              )}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="使用人">
              {getFieldDecorator('useOperator', {
                initialValue: currentItem.useOperator,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(
                <Select placeholder="请选择">
                  {usersByOrgId.map(item => (
                    <Option key={item.id} value={item.id}>
                      {item.realityName}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="所在位置">
              {getFieldDecorator('zcSeat', {
                initialValue: currentItem.zcSeat,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Select placeholder="请选择">{this.renderOptionNodes('location_seat')}</Select>)}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="状态">
              {getFieldDecorator('status', {
                initialValue: currentItem.status,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Select placeholder="请选择">{this.renderOptionNodes('property_status')}</Select>)}
            </FormItem>
          </Col>
        </Row>
        <div className={styles.fieldTitle}>其他信息</div>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="SN码">
              {getFieldDecorator('sn', {
                initialValue: currentItem.sn,
              })(<Input placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
          <div>
            <span style={{ lineHeight: '32px' }}>无SN码时可不填写</span>
          </div>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="RFID码">
              {getFieldDecorator('rfidCode', {
                initialValue: currentItem.rfidCode,
              })(<Input placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
          <div>
            <span style={{ lineHeight: '32px' }}>无RFID码时可不填写</span>
          </div>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="资产图片" extra="最多支持5张,图片大小需小于10M">
              {getFieldDecorator('filesImg', {
                initialValue: currentItem.items
                  ? { fileList: itemConvertToUpload('2', currentItem.items || []) }
                  : null,
              })(
                <Upload
                  showUploadList={{
                    showPreviewIcon: false,
                    showDownloadIcon: false,
                  }}
                  fileList={fileImgList}
                  accept=".jpg,.png,.PNG,.JPG,.JPEG,.jpeg"
                  action={`${settings.URL}/file/upload`}
                  listType="picture-card"
                  onChange={f => {
                    this.handleUplod(f, 'fileImgList')
                  }}
                  beforeUpload={this.handleBeforeUpload}
                  headers={AuthHeaders}
                >
                  {fileImgList.length >= 5 ? null : (
                    <div>
                      <Icon type="plus" />
                      <div className="ant-upload-text">上传</div>
                    </div>
                  )}
                </Upload>,
              )}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="资产附件" extra="上传转资表Excel附件，10M以下">
              {getFieldDecorator('filesfile', {
                initialValue: currentItem.items
                  ? { fileList: itemConvertToUpload('1', currentItem.items || []) }
                  : null,
              })(
                <Upload
                  showUploadList={{
                    showPreviewIcon: false,
                    showDownloadIcon: false,
                  }}
                  fileList={fileFileList}
                  accept=".xlsx,.cvx,.xls"
                  action={`${settings.URL}/file/upload`}
                  listType="text"
                  onChange={f => {
                    this.handleUplod(f, 'fileFileList')
                  }}
                  beforeUpload={this.handleBeforeUpload}
                  headers={AuthHeaders}
                >
                  {fileFileList.length >= 1 ? null : (
                    <Button type="default">
                      <Icon type="plus" />
                      上传
                    </Button>
                  )}
                </Upload>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={23} offset={1}>
            <FormItem label="备注">
              {getFieldDecorator('remark', {
                initialValue: currentItem.remark,
              })(<TextArea placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={24}>
            <Button
              style={{ marginLeft: 135 }}
              type="primary"
              onClick={() => {
                this.handleSave()
              }}
            >
              保存提交
            </Button>
          </Col>
        </Row>
      </Form>
    )
  }

  // 渲染界面
  render() {
    // const { dispatch, submitting } = this.props
    return (
      // TODO: 入库 or 编辑
      <PageHeaderWrapper title="资产入库">
        <div className={styles.myContainer}>
          <Card className={styles.noPadding} bordered={false}>
            {this.renderForm()}
          </Card>
        </div>
      </PageHeaderWrapper>
    )
  }
}
